/**
  ETFAna project, Anyang Normal University && IMP-CAS
  \class ETFDCTaL
  \brief a specification of ETFDCTa, with larger drift cells (10mm)
  \author SUN Yazhou, asia.rabbit@163.com
  \since 2022-04-25
  \date 2023-04-16 last modified
  \attention
  changelog
  <table>
  <tr>  <th>Date         <th>Author      <th>Description                   </tr>
  <tr>  <td>2022-04-25   <td>Asia Sun    <td>file created                  </tr>
  </table>

  \copyright Copyright (c) 2021-2024 Anyang Normal U. && IMP-CAS with LGPLv3 LICENSE
*/

#include <cmath>
#include "ETFDCTaL.h"
#include "ETFMsg.h"
#include "ETFParaManager.h"
#include "ETFYaml.h"
#include "ETFMath.h"

ETFDCTaL::ETFDCTaL(const char *name) : ETFDCTa(name){
  // configure the DC //
  fNL = 40;
  fSenseWireDistance = 10.; fMaxDL = fSenseWireDistance/2.;
  fLayerSpace12 = 10.; fLayerSpaceXY = 25.; fStagger12 = -5.;
  fX0Min = -192.5; // 7.5 - fSenseWireDistance*(fNL/2)

  // pass user trig bound and drift time bound parameters //
  const YAML::Node &trigBConfig = (*fpm->GetMisPara())["dcTaLTrigB"];
  if(trigBConfig){
    fTrigLB = trigBConfig[0].as<double>();
    fTrigHB = trigBConfig[1].as<double>();
  } // end if
  // pass user trig bound and drift time bound parameters //
  const YAML::Node &DTBConfig = (*fpm->GetMisPara())["dcTaLDTB"];
  if(DTBConfig){
    fDTLB = DTBConfig[0].as<double>();
    fDTHB = DTBConfig[1].as<double>();
  } // end if

  // fill channel id map //
  int cnt = 0; // type[0-2]: [X-Y, X1-2, cableId]
  for(const auto &chid : fChIdConfig){
    if(cnt && 0 == cnt%5){ type[1]++; type[2] = 0; } // X1-2
    if(cnt && 0 == cnt%10){ type[0]++; type[1] = 0; } // X-Y
    FillChIdMap(chid.as<int>());
    type[2]++; cnt++;
    if(cnt > 20) ETFMsg::Error("ETDCTaL", "ctor: cnt=%d > 20!", cnt);
  } // end for over cables
} // end ctor

ETFDCTaL::~ETFDCTaL(){}

// fill the channel map for X or Y wires
// XY, X1-X2, senseWireId
void ETFDCTaL::FillChIdMap(int chId0){
  if(chId0 < 0) return;
  for(int i = 0; i < 8; i++)
    //        chanel id      X-Y      X1-2   wireId=cableID*8+i=[0,39]
    SetChMap(chId0+i, uid(type[0], type[1], (type[2]<<3)+i));
} // end member function FillChIdMap

// r = r(t); drift distance - drift time relation
double ETFDCTaL::SpaceTimeRelation(double t){
  // usually STR at different HVs are so different as worth special treatment
  // be it a garfield simulation, or user-refined tuning based on experiment data analysis
  double r = 0.;
  const int POLN = fvstr.size();
  const double MAXR = fSenseWireDistance/2.;

  if(!POLN) r = ETFVDC::SpaceTimeRelation(t); // a parabola-form STR
  else for(int i = POLN; i--;) r += fvstr[i]*pow(t, i);
  if(r < 0. || t < -10.) r = 0.;
  if(r > MAXR || t > 285.) r = MAXR;

  return r;
} // end member function SpaceTimeRelation
